﻿using OperationPlugins.Handlers;
using OperationPlugins.Mvc;
using OperationPlugins.Mvc.Handlers;
using OperationPlugins.WebApp.ViewModes;
using System;

namespace OperationPlugins.WebApp.Handlers
{
    [HandlerOf(typeof(ActionMethodInfo))]
    public class ViewModelResourceProviderBinder : AbstractActionMethodHandler
    {
        protected override void Handle()
        {
            ViewModelBase vm = null;
            foreach (object parameter in Value.ActionParameters.Values)
            {
                vm = parameter as ViewModelBase;
                if (vm != null)
                {
                    break;
                }
            }

            if (vm != null)
            {
                IViewModelResourceProvider provider = Value.ActionExecutingContext.Controller as IViewModelResourceProvider;
                if (provider != null)
                {
                    Bind(provider, vm);
                }
            }
        }

        internal static void Bind(IViewModelResourceProvider provider, ViewModelBase vm)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            if (vm == null)
            {
                throw new ArgumentNullException("vm");
            }

            vm.ResourceProvider = provider;
        }

        internal static void Unbind(ViewModelBase vm)
        {
            if (vm == null)
            {
                throw new ArgumentNullException("vm");
            }

            vm.ResourceProvider = null;
        }

    }
}